package com.authorization.demo.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.authorization.demo.entity.UserTable;
import com.authorization.demo.excel.entity.UserExcel;
import com.authorization.demo.service.UserTableService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Remarks:
 * @ClassName: UserExcelListener
 * @Author: Micora
 * @CreateTime: 2022/8/1
 */
public class UserExcelListener extends AnalysisEventListener<UserExcel> {
    //因为UserExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    public UserTableService userTableService;
    public UserExcelListener(){}
    public UserExcelListener(UserTableService userTableService){
        this.userTableService = userTableService;
    }

    //读取excel内容，一行一行进行读取
    @Override
    public void invoke(UserExcel userExcel, AnalysisContext analysisContext) {
        if(userExcel == null){
            return;
        }
        //一行一行读取,每次读取多个值
        //手机号和邮箱合法之后，需要判断数据是否重复添加
        UserTable exist = this.existUser(userTableService, userExcel);
        System.out.println(exist == null);
        if(exist == null){//数据库中没有这条数据再进行插入
            UserTable userTable = new UserTable();
            userTable.setUserName(userExcel.getUserName());
            userTable.setPassword(userExcel.getPassword());
            userTable.setName(userExcel.getName());
            userTable.setGender(userExcel.getGender().equals("男")?1:2);
            userTable.setPhone(userExcel.getPhone());
            userTable.setMail(userExcel.getMail());
            userTable.setStatus(userExcel.getStatus().equals("有效")?1:0);
            userTable.setRemarks(userExcel.getRemarks());
            System.out.println(userTable);
            userTableService.save(userTable);
        }
    }

    //判断该用户信息是否能存入数据库
    private UserTable existUser(UserTableService userTableService , UserExcel userExcel){
        UserTable userTable = null;
        //匹配导入的手机号是否符合手机号的规范
        //手机号
        Pattern compile = Pattern.compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|199)\\d{8}$");

        //邮箱
        Pattern compile2 = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        Matcher matcher = compile.matcher(userExcel.getPhone());
        Matcher matcher2 = compile2.matcher(userExcel.getMail());
        if(matcher.find()&&(matcher2.find())){
            //根据用户名查询用户对象
            userTable = userTableService.getOne(new QueryWrapper<UserTable>()
                    .eq("USER_NAME", userExcel.getUserName()));
        }
        return userTable;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
